function [capacity,BCapacity,bbBits,bIndex]=GetImgCapacity(im, s)
[M,N]=size(im);
na=calNa(s);
p=max(ceil(log2(na)),1);
capacity=0; BCapacity=[];
bbBits=[]; bIndex=[];
for i=1:s:M
    for j=1:s:N
        block=im(i:i+s-1,j:j+s-1);
        [cb,qi,n0,n1,m,pos]=CalBlockCapacity(block, s, na,p);
        if cb==-2
            capacity=capacity-2;
            bbBits=[bbBits; block(1,1); block(1,2)];
            bIndex=[bIndex;0];
        else
            BCapacity(i,j).cb=cb;
            BCapacity(i,j).qi=qi;
            BCapacity(i,j).n0=n0;
            BCapacity(i,j).n1=n1;
            BCapacity(i,j).m=m;
            BCapacity(i,j).pos=pos;
            capacity=capacity+cb;
            bIndex=[bIndex;1];
        end
    end
end     
end


function [cb,qi,n0,n1,m,pos]=CalBlockCapacity(block, s, na,p)
block=block';
block=block(:);
n1=sum(block);
n0=s^2-n1;
m=min(n0,n1);
qi=[];pos=[];
if m==0
    cb=s^2-2;
elseif 1<=m&&m<=na
    if n0<n1
        pos=find(block==0);
    else
        pos=find(block==1);
    end
    qi=CalQi(m,s^2,pos);
    cb=s^2-3-p-sum(qi);
else
    cb=-2;
end
end

function qi=CalQi(m,n,pos)
qi=zeros(m,1);
if nargin<=2
    qi(1)=ceil(log2(n));
else
    for i=1:m
        if i==1
            qi(i)=ceil(log2(n));
        else
            qi(i)=max(ceil(log2(n-pos(i-1))),1);
        end
    end
end
end